package com.incar.chuxing.api;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.incar.chuxing.R;
import com.incar.chuxing.activity.MainActivity;
import com.incar.chuxing.activity.WebViewActivity;
import com.incar.chuxing.activity.WebViewNewUserActivity;
import com.incar.chuxing.activity.certification.CertifyCardActivity;
import com.incar.chuxing.activity.certification.CertifyCardInActivity;
import com.incar.chuxing.activity.certification.CertifyCardOkActivity;
import com.incar.chuxing.activity.personal.ContactServiceActivity;
import com.incar.chuxing.activity.personal.LoginActivity;
import com.incar.chuxing.activity.personal.TravelDetailActivity;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.bean.AvatarEvent;
import com.incar.chuxing.bean.DrawerEvent;
import com.incar.chuxing.bean.H5CancelOrderEvent;
import com.incar.chuxing.bean.UploadImageBaidu;
import com.incar.chuxing.bean.WXPreBean;
import com.incar.chuxing.payAndShare.AlipayUtils;
import com.incar.chuxing.payAndShare.WXPayUtils;
import com.incar.chuxing.payAndShare.WxLoginUtil;
import com.incar.chuxing.payAndShare.WxShareUtils;
import com.incar.chuxing.payAndShare.ZfbLoginUtil;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.Dialogs.ChooseAvatarDialog;
import com.incar.chuxing.utils.Dialogs.ChooseThirdShareDialog;
import com.incar.chuxing.utils.IntentKey;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.utils.RxBus;
import com.incar.chuxing.utils.SDCardUtils;
import com.incar.chuxing.utils.SPKey;
import com.incar.chuxing.utils.SPUtils;
import com.incar.chuxing.utils.bos.UploadPicUtil;
import com.incar.chuxing.utils.wangyiqiyu.ConsultService;
import com.linchaolong.android.imagepicker.ImagePicker;
import com.linchaolong.android.imagepicker.cropper.CropImage;
import com.linchaolong.android.imagepicker.cropper.CropImageView;
import com.qiyukf.unicorn.api.Unicorn;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.umeng.message.UTrack;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import wendu.dsbridge.CompletionHandler;

public class JsApiNewUser {
    private Context mContext;
    private WebViewNewUserActivity webViewActivity;
    private ImagePicker imagePicker;
    private File compressFile;
    private String key;
    private int submitType;
    private int NativeIdCardFront;

    public JsApiNewUser(Context context, WebViewNewUserActivity activity, ImagePicker imagePicker) {
        this.mContext = context;
        this.webViewActivity = activity;
        this.imagePicker = imagePicker;
    }

    //微信支付
    @JavascriptInterface
    public void wxPay(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge", msg.toString());
        SPUtils.getInstance(mContext).putIntValue(SPKey.USER_PAY_TYPE, 4);
        WXPayUtils wxPayUtils = new WXPayUtils(mContext);
        wxPayUtils.wxPay(new Gson().fromJson(((JSONObject) msg).toString(), WXPreBean.AttachmentBean.BeanBean.class));
        //handler.complete(" [ asyn call]");
    }

    //支付宝支付
    @JavascriptInterface
    public void aliPay(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge", msg.toString());
        SPUtils.getInstance(mContext).putIntValue(SPKey.USER_PAY_TYPE, 4);
        AlipayUtils alipayUtils = new AlipayUtils((Activity) mContext);
        alipayUtils.aliPay(((JSONObject) msg).optString("str"));
        //handler.complete(" [ asyn call]");
    }

    //跳转到订单详情
    @JavascriptInterface
    public void pushOrderInfo(Object msg, CompletionHandler<String> handler) {
        Intent intent = new Intent(mContext, TravelDetailActivity.class);
        intent.putExtra("orderId", ((JSONObject) msg).optString("orderId"));
        mContext.startActivity(intent);
        //handler.complete(" [ asyn call]");
    }

    //跳转到首页
    @JavascriptInterface
    public void pushIndex(Object msg, CompletionHandler<String> handler) {
        Intent intent = new Intent(mContext, MainActivity.class);
        intent.putExtra("jumpCode", 1);
        mContext.startActivity(intent);
    }

    //选择优惠券
    @JavascriptInterface
    public void chooseCoupons(Object msg, CompletionHandler<String> handler) {
        JSONObject jsonObject = (JSONObject) msg;
        /*Intent intent = new Intent(mContext, PaymentActivity.class);
        intent.putExtra("couponId", jsonObject.optString("couponId"));
        intent.putExtra("couponPrice", jsonObject.optString("couponPrice"));
        intent.putExtra("payPrice", jsonObject.optString("payPrice"));
        mContext.startActivity(intent);*/
        //handler.complete(" [ asyn call]");
    }

    //Webview标题
    @JavascriptInterface
    public void modifyNativeNavBarTitle(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge", msg.toString());
        JSONObject jsonObject = (JSONObject) msg;
        final String title = jsonObject.optString("title");
        Logger.d("jsbridgetitle", title);
        webViewActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webViewActivity.setTitle(title);
            }
        });

    }

    //finish current page
    @JavascriptInterface
    public void dissmissCurrentVc(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge", msg.toString());
        AppManager.getAppManager().finishActivity();
    }

    //添加导航栏右侧按钮
    @JavascriptInterface
    public void nativeAddNavRightItem(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge", msg.toString());
        JSONObject jsonObject = (JSONObject) msg;
        final String title = jsonObject.optString("title");
        final String color = jsonObject.optString("color");
        Logger.d("jsbridgetitle", title);
        webViewActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webViewActivity.setRightTitle(title);
                if (!TextUtils.isEmpty(color)) {
                    webViewActivity.setRightTitleColor(Color.parseColor(color));
                }
                webViewActivity.titleTvMore.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        handler.setProgressData("1");
                    }
                });
            }
        });
    }

    //隐藏掉右侧导航
    @JavascriptInterface
    public void nativeHideNavRightItem(Object msg, CompletionHandler<String> handler) {
        webViewActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webViewActivity.titleTvMore.setVisibility(View.INVISIBLE);
            }
        });
    }

    //隐藏掉左侧导航
    @JavascriptInterface
    public void hideNavLeftButton(Object msg, CompletionHandler<String> handler) {
        webViewActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webViewActivity.titleBack.setVisibility(View.INVISIBLE);
                webViewActivity.forbidBackPresses = true;
            }
        });
    }

    //显示左侧导航
    @JavascriptInterface
    public void showNavLeftButton(Object msg, CompletionHandler<String> handler) {
        webViewActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webViewActivity.titleBack.setVisibility(View.VISIBLE);
                webViewActivity.forbidBackPresses = false;
            }
        });
    }


    //跳到充值明细
    @JavascriptInterface
    public void pushRechargeBills(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge", msg.toString());
        Intent intent = new Intent();
        intent.setClass(mContext, WebViewActivity.class);
        intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "充值明细");
        intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_bill_detail));
        mContext.startActivity(intent);
    }

    //
    @JavascriptInterface
    public void needHandleExceptionOrder(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge", msg.toString());
        Intent intent = new Intent(mContext, MainActivity.class);
        intent.putExtra("jumpCode", 4);
        mContext.startActivity(intent);
    }


    @JavascriptInterface
    public String getOrderDetail(Object msg) {
        Logger.d("jsbridge", msg.toString());
        String orderDetail = SPUtils.getInstance(mContext).getStringValue("orderDetail");
        Logger.d("jsbridge", "orderDetail" + orderDetail + "");
        return "";
    }

    //获取图片
    @JavascriptInterface
    public void modelNativeChosePhotoController(Object msg, CompletionHandler<Object> handler) {
        Logger.d("jsbridge", msg.toString());
        JSONObject jsonObject = (JSONObject) msg;
        String type = jsonObject.optString("type");
        if (type.equals("systemPhotoVc")) {
            choosePic(handler);
        } else if (type.equals("idCardFrontVc")) {
            chooseIdfront();
        } else if (type.equals("idCardBackVc")) {

        } else if (type.equals("driveCardFrontVc")) {

        } else if (type.equals("driveCardBackVc")) {

        } else if (type.equals("selfVc")) {

        }
    }

    //获取图片
    @JavascriptInterface
    public void pushIdentityController(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge", msg.toString());
        JSONObject jsonObject = (JSONObject) msg;
        String fromType = jsonObject.optString("type");
        String status = jsonObject.optString("status");
        if (fromType.equals("fromNewUser")) {
            Intent intent = new Intent(mContext, CertifyCardActivity.class);
            intent.putExtra("intentFrom", 2);
            intent.putExtra("fromType", fromType);
            mContext.startActivity(intent);
        } else if (fromType.equals("authFlow")) {
            Intent intent = new Intent(mContext, CertifyCardActivity.class);
            intent.putExtra("fromType", fromType);
            mContext.startActivity(intent);
        } else {//type = fromUserCenter
            Logger.d("jsbridge", status + "--STATUS");
            if (status.equals("0")) {
                Intent intent = new Intent(mContext, CertifyCardActivity.class);
                intent.putExtra("fromType", fromType);
                mContext.startActivity(intent);
            } else if (status.equals("1")) {
                Intent intent = new Intent(mContext, CertifyCardOkActivity.class);
                intent.putExtra("fromType", fromType);
                mContext.startActivity(intent);
            } else {//status 2 认证中
                Intent intent = new Intent(mContext, CertifyCardInActivity.class);
                intent.putExtra("fromType", fromType);
                mContext.startActivity(intent);
            }
        }
    }

    //跳到充值明细
    @JavascriptInterface
    public void sesameCallbackUrl(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge", msg.toString());
        JSONObject jsonObject = (JSONObject) msg;
        String tbUrl = jsonObject.optString("tbUrl");
        doVerify(tbUrl);
    }

    //跳到客服
    @JavascriptInterface
    public void customerService(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge", msg.toString());
        if (Unicorn.isServiceAvailable()) {
            ConsultService consultService = new ConsultService(mContext);
            consultService.consultService(mContext, "", "", "", null);
        } else {
            Intent intent = new Intent(mContext, ContactServiceActivity.class);
            webViewActivity.startActivity(intent);
        }
    }

    //
    @JavascriptInterface
    public void changeUserInfo(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge", msg.toString());
        JSONObject jsonObject = (JSONObject) msg;
        String type = jsonObject.optString("type");
        String content = jsonObject.optString("content");
        if (type.equals("userName")) {
            SPUtils.getInstance(mContext).putStringValue(SPKey.USER_NICK, content);
            EventBus.getDefault().post(new AvatarEvent(true));
        } else if (type.equals("userPhoto")) {
            SPUtils.getInstance(mContext).putStringValue(SPKey.USER_PICTURE, key);
            EventBus.getDefault().post(new AvatarEvent(true));
        }
    }

    @JavascriptInterface
    public void userLogout(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge", "退出登录" + msg.toString());
        //退出登录
        try {
            webViewActivity.mPushAgent.deleteAlias(((MyApplication) MyApplication.getInstance()).getUid(), "USER", new UTrack.ICallBack() {
                @Override
                public void onMessage(boolean b, String s) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        Unicorn.logout();
        SPUtils.getInstance(mContext).clearSharePreference();
        EventBus.getDefault().post(new DrawerEvent(true));//通知抽屉可以打开否！
        ((MyApplication) MyApplication.getInstance()).setUid(null);
        ((MyApplication) MyApplication.getInstance()).setToken(null);
        ((MyApplication) MyApplication.getInstance()).setHeaderToken(null);
        Intent intent = new Intent(mContext, LoginActivity.class);
        mContext.startActivity(intent);
    }

    @JavascriptInterface
    public void shareSocialThirdParty(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge", msg.toString());
        JSONObject jsonObject = (JSONObject) msg;
        String type = jsonObject.optString("type");
        JSONObject data = jsonObject.optJSONObject("data");
        String inviteUrl = data.optString("url");
        Logger.d("jsbridge", inviteUrl);
        String inviteTitle = data.optString("title");
        String inviteDescroption = data.optString("descriptions");
        String inviteThumb = ((MyApplication) MyApplication.getInstance()).getImageUrl() + data.optString("picture");
        int shareType = 0;
        if (type.equals("1")) {
            shareType = 2;
        } else if (type.equals("2")) {
            shareType = 0;
        } else if (type.equals("3")) {
            shareType = 1;
        }
        inviteFriendsShare(shareType, inviteUrl, inviteTitle, inviteDescroption, inviteThumb);

    }

    @JavascriptInterface
    public void nativeShowThirdShare(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge", msg.toString());
        JSONObject jsonObject = (JSONObject) msg;
        JSONObject data = jsonObject.optJSONObject("data");
        String inviteUrl = data.optString("url");
        Logger.d("jsbridge", inviteUrl);
        String inviteTitle = data.optString("title");
        String inviteDescroption = data.optString("descriptions");
        String inviteThumb = ((MyApplication) MyApplication.getInstance()).getImageUrl() + data.optString("picture");
        final ChooseThirdShareDialog chooseThirdShareDialog = new ChooseThirdShareDialog(mContext);
        chooseThirdShareDialog.setOnItemClickListener(position -> {
            handler.setProgressData("1");
            inviteFriendsShare(position, inviteUrl, inviteTitle, inviteDescroption, inviteThumb);
            chooseThirdShareDialog.dismiss();
        });
        chooseThirdShareDialog.show();
    }

    private void inviteFriendsShare(int type, String url, String title, String description, String thumb) {
        if (type == 0 || type == 1) {//0微信  1朋友圈
            webViewActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    webViewActivity.showLoadingDialog();
                    WxShareUtils wxShareUtils = new WxShareUtils(mContext);
                    Glide.with(MyApplication.getInstance()).load(thumb).asBitmap().error(R.mipmap.ic_launcher).into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                            wxShareUtils.share(url, title, description, bitmap
                                    , type == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline);
                        }

                        @Override
                        public void onLoadFailed(Exception e, Drawable errorDrawable) {
                            wxShareUtils.share(url, title, description, ((BitmapDrawable) errorDrawable).getBitmap()
                                    , type == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline);
                        }
                    });
                }
            });

        } else if (type == 2) {//QQ
            webViewActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    UMWeb web = new UMWeb(url);
                    web.setTitle(title);
                    web.setDescription(description);
                    web.setThumb(new UMImage(mContext, thumb));
                    new ShareAction(webViewActivity).setPlatform(SHARE_MEDIA.QQ)
                            .withMedia(web)
                            .setCallback(umShareListener)
                            .share();
                }
            });
        }


    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            webViewActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    webViewActivity.showLoadingDialog();
                }
            });
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            webViewActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    webViewActivity.dismissLoadingDialog();
                }
            });
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            webViewActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    webViewActivity.dismissLoadingDialog();
                }
            });
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            webViewActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    webViewActivity.dismissLoadingDialog();
                }
            });
        }
    };

    private void choosePic(CompletionHandler<Object> handler) {
        //跳转图片选择
        final ChooseAvatarDialog chooseAvatarDialog = new ChooseAvatarDialog(mContext);
        chooseAvatarDialog.setOnItemClickListener(new ChooseAvatarDialog.OnItemClickListener() {
            @Override
            public void onClickItem(int position) {
                chooseAvatarDialog.dismiss();
                ImagePicker.Callback callback = new ImagePicker.Callback() {
                    // 选择图片回调
                    @Override
                    public void onPickImage(Uri imageUri) {
                    }

                    // 裁剪图片回调
                    @Override
                    public void onCropImage(Uri imageUri) {
                        compressFile = new File(imageUri.getPath());
                        uploadImage(compressFile, handler);
                    }

                    // 自定义裁剪配置
                    @Override
                    public void cropConfig(CropImage.ActivityBuilder builder) {
                        builder
                                // 是否启动多点触摸
                                .setMultiTouchEnabled(false)
                                // 设置网格显示模式
                                .setGuidelines(CropImageView.Guidelines.ON_TOUCH)
                                // 圆形/矩形
                                .setCropShape(CropImageView.CropShape.RECTANGLE)
                                // 调整裁剪后的图片最终大小
                                .setRequestedSize(400, 400)
                                // 宽高比
                                .setAspectRatio(1, 1);
                    }

                    // 用户拒绝授权回调
                    @Override
                    public void onPermissionDenied(int requestCode, String[] permissions,
                                                   int[] grantResults) {
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("error", "error");
                            handler.setProgressData(jsonObject);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };
                if (position == 0) {
                    imagePicker.startCamera(webViewActivity, callback);
                } else if (position == 1) {
                    imagePicker.startGallery(webViewActivity, callback);
                }
            }
        });
        chooseAvatarDialog.show();
    }

    private void chooseIdfront() {

    }

    //获得要上传图片的参数，并上传图片
    private void uploadImage(final File picFile, CompletionHandler<Object> handler) {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).uploadImageBaidu(((MyApplication) MyApplication.getInstance()).getRequestFieldMap(), "stsToken", "upload").enqueue(new Callback<UploadImageBaidu>() {
            @Override
            public void onResponse(Call<UploadImageBaidu> call, Response<UploadImageBaidu> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        key = SDCardUtils.createFileName(((MyApplication) MyApplication.getInstance()).getUid());
                        UploadPicUtil.getInstance().uploadPicToBos(picFile, response.body().getAttachment().getAk(),
                                response.body().getAttachment().getSk(), response.body().getAttachment().getBucketName(),
                                response.body().getAttachment().getStsToken(),
                                response.body().getAttachment().getBucketName(),
                                key, new UploadPicUtil.OnFinishListener() {
                                    @Override
                                    public void onSuccess() {
                                        Message message = new Message();
                                        message.arg1 = 4;
                                        Bundle b = new Bundle();
                                        message.setData(b);
                                        try {
                                            JSONObject jsonObject = new JSONObject();
                                            jsonObject.put("imageId", key);
                                            handler.setProgressData(jsonObject);
                                            Logger.d("jsbridge_return", "imageId:" + key);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onFailure(String failReason) {
                                        Message message = new Message();
                                        message.arg1 = 5;
                                        Bundle b = new Bundle();
                                        b.putString("failReason", failReason);
                                        message.setData(b);
                                        try {
                                            JSONObject jsonObject = new JSONObject();
                                            jsonObject.put("error", failReason);
                                            handler.setProgressData(jsonObject);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                    } else {
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("error", "error");
                            handler.setProgressData(jsonObject);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("error", "error");
                        handler.setProgressData(jsonObject);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<UploadImageBaidu> call, Throwable t) {
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("error", "error");
                    handler.setProgressData(jsonObject);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 启动支付宝进行认证
     *
     * @param url 开放平台返回的URL
     */
    private void doVerify(String url) {
        if (hasApplication()) {
            SPUtils.getInstance(mContext).putStringValue(SPKey.INTENT_ZHIMA, "WebViewActivity");
            Intent action = new Intent(Intent.ACTION_VIEW);
            StringBuilder builder = new StringBuilder();
            // 这里使用固定appid 20000067
            builder.append("alipays://platformapi/startapp?appId=20000067&url=");
            builder.append(URLEncoder.encode(url));
            action.setData(Uri.parse(builder.toString()));
            mContext.startActivity(action);
        } else {
            // 处理没有安装支付宝的情况
            new AlertDialog.Builder(mContext)
                    .setMessage("是否下载并安装支付宝完成认证?")
                    .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent action = new Intent(Intent.ACTION_VIEW);
                            action.setData(Uri.parse("https://m.alipay.com"));
                            mContext.startActivity(action);
                        }
                    }).setNegativeButton("算了", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();
        }
    }

    /**
     * 判断是否安装了支付宝
     *
     * @return true 为已经安装
     */
    private boolean hasApplication() {
        PackageManager manager = mContext.getPackageManager();
        Intent action = new Intent(Intent.ACTION_VIEW);
        action.setData(Uri.parse("alipays://"));
        List list = manager.queryIntentActivities(action, PackageManager.GET_RESOLVED_FILTER);
        return list != null && list.size() > 0;
    }

    //支付宝登录授权
    @JavascriptInterface
    public void nativeForAliPayAuthRequestWithParams(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge zfbAuth", msg.toString());
        ZfbLoginUtil zfbLoginUtil = new ZfbLoginUtil(webViewActivity);
        JSONObject jsonObject = (JSONObject) msg;
        zfbLoginUtil.zfbLogin(jsonObject.optString("infoStr"));
    }

    //微信登录授权
    @JavascriptInterface
    public void nativeForWechatAuthRequestWithParams(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge wxAuth", msg.toString());
        WxLoginUtil wxLoginUtil = new WxLoginUtil(webViewActivity);
        JSONObject jsonObject = (JSONObject) msg;
        wxLoginUtil.wxLogin(jsonObject.optString("appId"), jsonObject.optString("scope"), jsonObject.optString("state"));
    }


    @JavascriptInterface
    public void setNativeCookie(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge wxAuth", msg.toString());
        JSONObject jsonObject = (JSONObject) msg;
        SPUtils.getInstance(mContext).putStringValue(jsonObject.optString("key"), jsonObject.optString("value"));
    }


    @JavascriptInterface
    public String getNativeCookie(Object msg) {
        Logger.d("jsbridge", msg.toString());
        return ((MyApplication) MyApplication.getInstance()).getCookieMap().get(msg.toString());
    }

    @JavascriptInterface
    public Map<String, String> getNativeCookies(Object msg) {
        Logger.d("jsbridge", msg.toString());
        return ((MyApplication) MyApplication.getInstance()).getCookieMap();
    }

    @JavascriptInterface
    public void setNativePersistence(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge wxAuth", msg.toString());
        JSONObject jsonObject = (JSONObject) msg;
        SPUtils.getInstance(mContext).putStringValue(jsonObject.optString("key"), jsonObject.optString("value"));
    }

    @JavascriptInterface
    public String getNativePersistence(Object msg) {
        Logger.d("jsbridge", msg.toString());
        return SPUtils.getInstance(mContext).getStringValue(msg.toString());
    }

    @JavascriptInterface
    public void callPhone(Object msg) {
        Logger.d("jsbridge", msg.toString());
        JSONObject jsonObject = (JSONObject) msg;
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + jsonObject.optString("phoneNum")));
        mContext.startActivity(intent);
    }


    @JavascriptInterface
    public void cancleOrderSuccess(Object msg) {
        Logger.d("jsbridge", "H5订单取消成功");
        RxBus.getInstance().post(new H5CancelOrderEvent(true));
    }
}
